"""
Tag manipulation views
"""

from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

from track.models import Vehicle
from live.models  import Tag
from live.models  import VehicleTag

@login_required
def set_public(request, tag, public):
  """Make a tag public or private"""
  tag = get_object_or_404(Tag, slug=tag, user=request.user)
  
  tag.is_public = True if public == 'True' else False
  
  tag.save()
  
  return HttpResponseRedirect('/live/')

@login_required
def new(request, tag):
  """Create a new tag"""
  from django.template.defaultfilters import slugify
  
  Tag(name=tag, slug=slugify(tag), user=request.user).save()
  
  return HttpResponseRedirect('/live/')

@login_required
def delete(request, tag):
  """Delete a tag"""
  tag = get_object_or_404(Tag, slug=tag, user=request.user)
  
  tag.delete()
  
  return HttpResponseRedirect('/live/')

@login_required
def add(request, tag, vehicle):
  """Add a tag to a vehicle"""
  tag     = get_object_or_404(Tag,     slug=tag, user=request.user)
  vehicle = get_object_or_404(Vehicle, slug=vehicle)
  
  VehicleTag(tag=tag, vehicle=vehicle).save()
  
  return HttpResponseRedirect('/live/')

@login_required
def remove(request, tag, vehicle):
  """Remove a tag from a vehicle"""
  vehicletag = get_object_or_404(VehicleTag, tag__slug=tag, tag__user=request.user, vehicle__slug=vehicle)
  
  vehicletag.delete()
  
  return HttpResponse()
